<template>
    <div ref="dom" class="chart" />
</template>

<script setup lang="ts">

import {defineProps, onMounted, ref, Ref, watch}                                           from "vue";
import * as echarts                                                                        from "echarts/core";
import {GeoComponent, LegendComponent, TitleComponent, ToolboxComponent, TooltipComponent} from "echarts/components";
import {MapChart, PieChart, ScatterChart}                                                  from "echarts/charts";
import {CanvasRenderer}                                                                    from "echarts/renderers";
import {useEventListener}                                                                  from "@vueuse/core";
import {sizeConfig}                                                                        from "@/views/main/dashboard/config";
import obj2arr                                                                             from "@/utils/obj2arr";
import {options}                                                                           from "@/views/main/dashboard/info/pieSize/options";

const props = defineProps({
    gardenList: {
        type   : Array,
        default: []
    },
    province  : String
})

watch(() => props.province, (newName: any) => {
    jumpTo(newName)
});

// dom元素
const dom: Ref<HTMLDivElement> = ref(null) as any

// eChart 实例
let myEchart: echarts.ECharts | null = null

// 使用Echart
function useEchart() {
    return new Promise((resolve) => {
        echarts.use([
            CanvasRenderer, MapChart, ScatterChart, GeoComponent, TitleComponent, TooltipComponent, ToolboxComponent, LegendComponent, PieChart
        ]);
        myEchart = echarts.init(dom.value)

        useEventListener("resize", () => myEchart!.resize()) // 页面尺寸变化,echart同步变化
        resolve("ok")
    })
}

/**
 * 绘画
 */
function jumpTo(name: string) {
    // 原始数据
    let gardenList = name === "全国" ? props.gardenList : props.gardenList?.filter((one: any) => one.province === name)

    let mySize = structuredClone(sizeConfig)
    // 类型热点数据提取
    gardenList.forEach((cur: any) => {
        mySize[cur.size].value += 1
    })

    options.series[0].data = obj2arr(mySize, "name")
    myEchart?.setOption(options)
}


// --------------------------- 生命函数 ---------------------------
onMounted(() => {
    useEchart().then(() => jumpTo("全国"))
})

</script>

<style lang="scss" scoped>
.chart {
    width: 100%;
    height: 50%;
}
</style>
